<template>
	<el-form ref="loginForm" :model="form" :rules="rules" label-width="0" size="large">
		<el-form-item prop="username">
			<el-input v-model="form.username" prefix-icon="el-icon-user" clearable
					  :placeholder="$t('login.userPlaceholder')">
			</el-input>
		</el-form-item>
		<el-form-item prop="password">
			<el-input v-model="form.password" prefix-icon="el-icon-lock" clearable show-password
					  :placeholder="$t('login.PWPlaceholder')"></el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" style="width: 100%;" round @click="login">{{
					$t('login.signIn')
				}}
			</el-button>
		</el-form-item>
		<div class="login-reg">
			{{ $t('login.noAccount') }}
			<router-link to="/user_register">{{ $t('login.createAccount') }}</router-link>
		</div>
	</el-form>
</template>

<script>
export default {
	data() {
		return {
			form: {
				username: "",
				password: "",
			},
			rules: {
				username: [
					{required: true, message: this.$t('login.userError'), trigger: 'blur'}
				],
				password: [
					{required: true, message: this.$t('login.PWError'), trigger: 'blur'}
				]
			},
		}
	},
	methods: {
		async login() {
			var validate = await this.$refs.loginForm.validate().catch(() => {
			})
			if (!validate) {
				return false
			}

			var data = {
				username: this.form.username,
				password: this.form.password
			}
			//获取token
			var user = await this.$API.auth.login.post(data)
			this.$TOOL.cookie.set("TOKEN", user.token, {
				expires: 24 * 60 * 60
			})
			window.sessionStorage.setItem('token', user.token)
			window.sessionStorage.setItem('username', user.username)
			this.$TOOL.cookie.set("token", user.token, {
				expires: 24 * 60 * 60
			})
			this.$TOOL.data.set("USER_INFO", user.userInfo)

			//获取菜单
			var menu = null
			menu = await this.$API.system.menu.myMenus.get()
			if (menu.code === 200) {
				if (menu.data.menu.length === 0) {
					this.$alert("当前用户无任何菜单权限，请联系系统管理员", "无权限访问", {
						type: 'error',
						center: true
					})
					return false
				}
				this.$TOOL.data.set("MENU", menu.data.menu)
				this.$TOOL.data.set("PERMISSIONS", menu.data.permissions)
			} else {
				this.$message.warning(menu.message)
				return false
			}

			this.$router.replace({
				path: '/'
			})
			this.$message.success("Login Success 登录成功")
		}
	}
}
</script>

<style>
</style>
